// pages/my/my.js
const wxaUserService = require('../../../../api/wxaUserService.js')
const orderService = require('../../../../api/orderService.js')
const couponService = require('../../../../api/couponService.js')
const memberService = require('../../../../api/memberService.js')
const redPacketService = require('../../../../api/redPacketService.js')
const auth = require('../../../../utils/auth.js')
const utils = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabbar: {},
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    member: {
      couponNum: 0
    },
    isMember: false,
    unPayNum: '',
    unGroupNum: '',
    unSelftakeNum: '',
    sendingNum: '',
    unEvaluateNum: '',
    waitPayBalance: '',
    tabSelected: 0,
    serviceTel: '',
    reserveBalance: 0,
    memberScoreBalabce: '0',
    redPacketBalance: '0.00',
    APP_VERSION: '1.0.0.3',
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false
    },
    overlayStyle: 'background: rgba(255, 255, 255, 0.9)',
    showTabbar: true
  },
  // 处理 Access Token 已过期
  handleLoginStatus: function (error) {
    if (error.code !== 20) {
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.editTabbar();
    const that = this
    this.setData({
      serviceTel: app.globalData.servicePhone
    })
    try {
      var tokens = auth.getTokens();
      const user = auth.getUser();
      const tempMember = that.data.member
      if (app.globalData.userInfo) {
        console.log('刷新时间：', utils.timestampToTime(tokens.expiresTo))
        console.log('到期时间：', utils.timestampToTime(tokens.refreshExpiresTo))
        console.log(tokens.refreshExpiresTo)
        // 691200000
        if (new Date().getTime() < tokens.refreshExpiresTo) {
          if (app.globalData.userInfo.wxaUser) {
            if (!app.globalData.userInfo.member) {
              wx.showToast({
                title: "您还不是会员，请绑定手机号成为会员",
                icon: 'none',
                duration: 2000
              })
              that.setData({
                userInfo: user.wxaUser,
                member: {
                  ...tempMember,
                  nickName: user.wxaUser.nickName
                },
                hasUserInfo: true,
                isMember: false
              })
            } else {
              that.setData({
                userInfo: user.wxaUser,
                member: {
                  ...tempMember,
                  ...user.member,
                  nickName: user.member.nickName ? user.member.nickName : user.wxaUser.nickName
                },
                hasUserInfo: true,
                isMember: true
              })
              that.getOrderStatusCount()
              that.getMemberInfo()
            }
          } else {
            // 还未登陆
            that.setData({
              hasUserInfo: false,
              isMember: false
            })
            wx.showToast({
              title: "您还未授权，请点击头像授权",
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          // accessTokens 过期 需要重新登录
          // auth.clearTokens();
          app.globalData.userInfo = null
          wx.showToast({
            title: "您还未授权，请点击头像授权",
            icon: 'none',
            duration: 2000
          })
          this.setData({
            hasUserInfo: false,
            isMember: false
          })
        }
      } else {
        wx.showToast({
          title: "您还未授权，请点击头像授权",
          icon: 'none',
          duration: 2000
        })
      }
    } catch (e) {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    }
    if (that.options.mobile && that.options.mobile != '' && that.options.mobile != undefined) {
      const mobile = that.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },
  getUserInfo: function (e) {
    console.log(e)
    const that = this
    wx.setStorage({
      key: "wj_userInfo",
      data: e.detail.userInfo
    })
    wxaUserService.login().then(res => {
      console.log(res)
      auth.setUser(res)
      app.globalData.userInfo = res
      if (!res.member) {
        that.setData({
          isMember: false,
          userInfo: e.detail.userInfo,
          hasUserInfo: true,
          member: {
            couponNum: 0
          }
        })
        wx.navigateTo({
          url: '../bindMobile/bindMobile'
        })
      } else {
        that.setData({
          member: {
            ...that.data.member,
            ...res.member,
            nickName: res.member.nickName ? res.member.nickName : res.wxaUser.nickName
          },
          isMember: true,
          userInfo: {
            ...e.detail.userInfo,
          },
          hasUserInfo: true
        })
        wx.setStorage({
          key: "wj_member",
          data: res.member
        })
        that.getOrderStatusCount()
        that.getMemberInfo()
      }
      that.handlePageSkip()
    }).catch(err => {
      console.log(err)
      let msg = 'meet frequency limit'
      let authorize = 'auth deny'
      let errMsg = err.message
      this.setData({
        isMember: false,
        hasUserInfo: false
      })
      if (errMsg.indexOf(msg) > -1) {
        wx.showToast({
          title: "登陆超时，请小憩片刻再来登陆吧~",
          icon: 'none',
          duration: 2000
        })
      } else if (errMsg.indexOf(authorize) > -1) {
        wx.showToast({
          title: "授权失败，请点击头像重新登录~",
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: "登陆失败，请点击头像重新登录~",
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 检查当前用户是否登录授权
  checkAuth: function (e) {
    console.log(e)
    var self = this;
    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请同意授权获取用户信息',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            self.getUserInfo(e)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    } else {
      return true;
    }
  },

  getMemberInfo: function () {
    const that = this;
    couponService.getMbrUnUseCouponCount().then(res => {
      console.log(res)
      let tempMember = that.data.member
      tempMember = {
        ...tempMember,
        couponNum: res
      }
      that.setData({
        member: tempMember
      })
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
    memberService.getMbrBalance().then(res => {
      if (res) {
        that.setData({
          reserveBalance: res.toFixed(2)
        })
      }
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
    memberService.getBalance(that.data.member.mobile).then(res => {
      console.log(res)
      that.setData({
        memberScoreBalabce: res
      })
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(app.globalData.userInfo)
    let user = auth.getUser()
    const self = this
    if (app.globalData.userInfo) {
      if (self.data.hasUserInfo === true && self.data.member.mobile) {
        self.setData({
          member: {
            ...self.data.member,
            ...user.member,
            nickName: user.member.nickName ? user.member.nickName : user.wxaUser.nickName
          },
          userInfo: {
            ...user.wxaUser
          },
        })
        self.getOrderStatusCount()
        self.getMemberInfo()
        self.handelRedPacketBalance()
      } else {
        if (!app.globalData.userInfo.member) {
          console.log(self.data.member)
          this.setData({
            isMember: false,
            userInfo: {
              ...user.wxaUser
            },
            member: {
              ...self.data.member,
              nickName: user.wxaUser.nickName
            }
          })
          // wx.showToast({
          //   title: "您还不是会员，请绑定手机号成为会员",
          //   icon: 'none',
          //   duration: 2000
          // })
        } else {
          self.setData({
            member: {
              ...self.data.member,
              ...user.member,
              nickName: user.member.nickName ? user.member.nickName : user.wxaUser.nickName
            },
            hasUserInfo: true,
            isMember: true,
          })
          self.getOrderStatusCount()
          self.getMemberInfo()
          self.handelRedPacketBalance()
        }
      }
    } else {
      wx.showToast({
        title: "您还未授权，请点击头像授权",
        icon: 'none',
        duration: 2000
      })
      self.setData({
        hasUserInfo: false,
        isMember: false,
        userInfo: {},
        member: {}
      })
    }
  },
  getOrderStatusCount: function () {
    const that = this
    let postData = {
      page: 1,
      pageSize: 0,
      searchCount: true,
      businessEquals: 'RETAIL_CATERING'
    }
    orderService.query(postData).then(res => {
      const that = this
      console.log(res)
      let stateInfo = {
        unGroupNum: 0,
        unSelftakeNum: 0,
        sendingNum: 0,
        unEvaluateNum: 0,
        unPayNum: 0,
        waitPayBalance: 0
      }
      var i = 0;
      var j = 0;
      var k = 0;
      var e = 0;
      var p = 0;
      var q = 0
      res.records.forEach(item => {
        if (item.status === "PAID" && item.teamId != '' && item.teamId != null && item.canRefund === true) {
          i++
          stateInfo.unGroupNum = i;
        }
        if (item.status === "PENDING" && item.canRefund === true) {
          j++
          stateInfo.unSelftakeNum = j;
        }
        if (item.status === "SHIPPED" && item.canRefund === true) {
          k++
          stateInfo.sendingNum = k;
        }
        if (item.status === "RECEIVED" && item.canRefund === true) {
          e++
          stateInfo.unEvaluateNum = e;
        }
        if (item.status === "WAITPAYBALANCE" && item.canRefund === true) {
          p++
          stateInfo.waitPayBalance = p;
        }
        if (item.status === "CREATED" && item.canRefund === true) {
          q++
          stateInfo.unPayNum = q;
        }
      })
      this.setData({
        unSelftakeNum: stateInfo.unSelftakeNum,
        unGroupNum: stateInfo.unGroupNum,
        sendingNum: stateInfo.sendingNum,
        unEvaluateNum: stateInfo.unEvaluateNum,
        waitPayBalance: stateInfo.waitPayBalance,
        unPayNum: stateInfo.unPayNum
      })
    }).catch(e => {
      if (e.message != 'Access Token没有设置') {
        that.handleLoginStatus(e)
      }
    })
  },

  /**
   * 调用接口查询红包余额
   */
  handelRedPacketBalance() {
    redPacketService.getBalance().then(res => {
      console.log(res)
      this.setData({
        redPacketBalance: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/member/my/my?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/member/my/my',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },
  toMemberInfo: function () {
    if (app.globalData.userInfo.member) {
      wx.navigateTo({
        url: '../memberInfo/memberInfo'
      })
    } else {
      wx.showToast({
        title: "您还不是会员，请绑定手机号成为会员",
        icon: 'none',
        duration: 2000
      })
    }
  },
  toMyDistribution: function () {
    wx.navigateTo({
      url: '../../distribution/myDistribution/myDistribution'
    })
  },
  toCoupon: function () {
    wx.navigateTo({
      url: '../../coupon/myCoupon/myCoupon'
    })
  },
  toCouponCenter: function () {
    wx.navigateTo({
      url: '../../coupon/couponCenter/couponCenter'
    })
  },
  toScore: function () {
    wx.navigateTo({
      url: '../../score/score/score'
    })
  },
  toRedPacket: function () {
    wx.navigateTo({
      url: '../redPacket/redPacket'
    })
  },
  toRecharge: function () {
    wx.navigateTo({
      url: '../../myCard/recharge/recharge'
    })
  },
  toAddress: function () {
    wx.navigateTo({
      url: '../../member/address/addressList/addressList'
    })
  },
  toSystem: function () {
    wx.navigateTo({
      url: '../system/system'
    })
  },
  // 邀请新人
  toInvite: function () {
    wx.navigateTo({
      url: '../../invite/invite'
    })
  },
  // 会员码
  toMemberCard: function () {
    wx.navigateTo({
      url: '../../myCard/memberCard/memberCard'
    })
  },
  // 去评价
  toEvaluate: function () {
    wx.navigateTo({
      url: '../../order/evaluate/evaluate'
    })
  },
  // 跳转到我的礼品卡
  toGiftCard: function () {
    wx.navigateTo({
      url: '../../../memberModule/giftCard/giftCard/giftCard',
    })
  },
  toCustomerService: function () {
    // wx.navigateTo({
    //   url: '../index/index'
    // })
  },
  toAllOrder: function () {
    wx.navigateTo({
      url: '../../order/order/order'
    })
  },
  toBalance: function () {
    wx.navigateTo({
      url: '../../myCard/balance/balance'
    })
  },
  toOrderMenu: function (val) {
    let selected = val.currentTarget.dataset.inx
    wx.navigateTo({
      url: '../../order/order/order?selected=' + selected
    })
  },
  toWaitPayedTailOrder: function () {
    wx.navigateTo({
      url: '../../order/order/order?type=payedTail'
    })
  },
  callPhone: function () {
    const tel = this.data.serviceTel
    wx.showModal({
      title: '提示',
      content: '确认要拨打此电话' + tel + ' ？',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: tel,
          })
        } else if (res.cancel) {}
      }
    })
  },
  // 处理其他页面跳转
  handlePageSkip() {
    const that = this
    try {
      // 获取其他页面传来的页面信息
      var pageUrl = wx.getStorageSync('wj_pageUrl')
      if (pageUrl) {
        console.log(pageUrl)
        // Do something with return value
        wx.navigateTo({
          url: pageUrl
        })
      }
      wx.removeStorageSync('wj_pageUrl')
    } catch (e) {
      // Do something when catch error
    }

  },
  recorderPopup: function () {
    this.toggleBottomPopup()
  },
  /**
   * 打开分享弹窗
   */
  toggleBottomPopup() {
    this.toggle('middle');
  },
  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type],
      [`overlayStyle`]: this.data.overlayStyle
    });
  },

  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          member: {
            ...self.data.member,
            ...user.member,
            nickName: user.member.nickName ? user.member.nickName : user.wxaUser.nickName
          },
          hasUserInfo: true,
          isMember: true,
        })
        self.getOrderStatusCount()
        self.getMemberInfo()
      } else {
        this.setData({
          isMember: false,
          member: {
            ...self.data.member,
            nickName: user.wxaUser.nickName
          }
        })
      }
    }
  },
  // 处理底部tabbar
  handleTabbar: function (e) {
    console.log(e.detail)
    if (e.detail.showTabbar === true) {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    } else {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    }
  }
})